import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Modal, Form, message } from 'antd';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { connect } from 'react-redux';
import BrandManagementStyle from './BrandManagement.module.css'
import Store from './../../store/index';
import { useRef } from 'react';
import * as Action from '../../store/actions/goods/action'


// 1.映射State到props:
function mapStateToProps(state) {
    console.log("222222", state);
    return {
        data: state.GoodsAttr.BrandManage
    }
}
// 2. 映射方法到props:
function mapDispatchToProps(dispatch) {
    return {
        BrandEdit: (id, obj) => { dispatch(Action.BrandEditBtn(id, obj)) },
        BrandDel: (id) => { dispatch(Action.BrandDelBtn(id)) },
        BrandAdd: (obj) => { dispatch(Action.BrandAddBtn(obj)) }
    }
}
const BrandManagement = (props) => {
    // console.log("props", props);
    const { BrandAdd, BrandEdit, BrandDel } = props
    const { confirm } = Modal;
    // 打开关闭模态框
    const [open, setOpen] = useState(false);
    const [open2, setOpen2] = useState(false);
    // 添加编辑标题titleMap
    const [titleMap, setTitleMap] = useState()
    // 查询
    const [bName, setBNme] = useState()

    // 添加
    const [addForm] = Form.useForm()
    // 修改
    const [editForm] = Form.useForm()
    const [columns, setColumns] = useState([
        { title: '品牌名称', dataIndex: 'name', key: 'name', },
        {
            title: '排序', dataIndex: 'sort', key: 'sort',
        },
        {
            title: '创建时间', dataIndex: 'date1', key: 'date1',
        },
        {
            title: '操作', dataIndex: '',
            render: (text) => (
                <div>
                    <Button type="link" onClick={() => edit1(text)}>编辑</Button>
                    <Button type="link" onClick={() => del(text)}>删除</Button>
                </div>
            )
        },

    ]);

    const [data, setData] = useState(Store.getState().GoodsAttr.BrandManage);


    const BNmeChange = (e) => {
        setBNme(e.target.value)

    }
    // 查询函数
    const queryFn = (e) => {
        // let list=[]
        // props.data.forEach(el => {
        //     const condition = (bName !== '' && el.name.includes(bName))
        //     if (condition) {
        //         list.push(el)
        //     }
        //     console.log("list", list);
        // })
        // setData(list)
        clearTimeout(window.timer)//防抖查询
        window.timer = setTimeout(() => {
            if (bName !== '') {
                let list = props.data.filter(el => el.name.includes(bName))
                setData(list)
            }
            if (bName === undefined || bName === '') {
                setData(data)
            }
        }, 500)
    }
    // 删除函数
    const del = (obj) => {
        confirm({
            title: '你确定删除当前行吗',
            icon: <ExclamationCircleFilled />,
            content: '',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                BrandDel(obj.id)
                setData(JSON.parse(JSON.stringify(Store.getState().GoodsAttr.BrandManage)))
                message.success('删除成功')
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }


    // 模态框取消按钮
    const onCannel = () => {
        console.log('Clicked cancel button');
        setOpen(false);
    };
    // 新增函数
    const openBrand = (id) => {
        addForm.setFieldsValue({
            "id": data.length + 1,
            "key": data.length + 1
        })
        setOpen(true);

        setTitleMap('添加品牌')

    }
    // 模态框确认按钮
    const handleOk = (values) => {
        console.log('Success:', values);
        BrandAdd(values)
        setData(JSON.parse(JSON.stringify(Store.getState().GoodsAttr.BrandManage)))
        setOpen(false);
        addForm.resetFields()
        message.success('操作成功')

    };
    // 编辑函数
    const edit1 = (obj) => {
        let showData = {}
        data.forEach(element => {
            if (element.id === obj.id) {
                console.log("element", element);
                showData = JSON.parse(JSON.stringify(element))
            }
        });
        console.log("show", showData);
        editForm.setFieldsValue({ ...showData })
        setOpen2(true)
    }

    // 编辑模态框确定按钮
    const handleOk2 = (values) => {
        BrandEdit(values.id, { ...values })
        setData(JSON.parse(JSON.stringify(Store.getState().GoodsAttr.BrandManage)))
        setOpen2(false);
        message.success('操作成功')
        editForm.resetFields()

    };
    // 编辑模态框取消按钮
    const onCannel2 = () => {
        console.log('Clicked cancel button');
        setOpen2(false);
    };

    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
        message.warning('操作失败，请重试')
    };
    // 获取当前时间
    const getCurrentTime = () => {
        var date = new Date();
        let Y = date.getFullYear() + '-';
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        let D = date.getDate() + ' ';
        let h = date.getHours() + ':';
        let m = date.getMinutes() + ':';
        let s = date.getSeconds();

        let currentTime = Y + M + D + h + m + s
        return currentTime
    }
    let [getTimes, setGetTimes] = useState(getCurrentTime())
    // 表格分页
    const [tableParams, setTableParams] = useState({
        pagination: {
            current: 1,
            pageSize: 3,
        },
    });
    const fetchData = () => {
        setTableParams({
            ...tableParams,
            pagination: {
                ...tableParams.pagination,
                total: data.length,
            },
        });
    }
    useEffect(() => {
        fetchData();
    }, [JSON.stringify(tableParams), data]);
    // 分页总条数的显示
    const showTotal = (total) => {
        return `总共${total}条`
    }
    //表格页数变化
    const handleTablePageChange = (pagination, filters, sorter) => {
        setTableParams({
            pagination,
            filters,
            ...sorter,
        });
    }
    return (
        <>
            <div className={BrandManagementStyle.title}>
                <div >
                    <Button type="primary" className={BrandManagementStyle.titleLeft} onClick={() => openBrand()}>新建品牌</Button>
                </div>


                <div className={BrandManagementStyle.titleR}>
                    <Input placeholder="请输入品牌名称" style={{ width: '200px' }} value={bName} onChange={BNmeChange} />
                    <Button type="primary" className={BrandManagementStyle.titleLeft} onClick={() => queryFn()}>查询</Button>

                </div>
            </div>
            <Table columns={columns} dataSource={data} pagination={
                {
                    ...tableParams.pagination,
                    showSizeChanger: true,
                    showTotal,
                    pageSizeOptions: [3, 5, 8, 10]
                }
            }
                onChange={handleTablePageChange} />
            <Modal
                title={titleMap}
                open={open}
                closable={false}
                footer={null}
            >
                <Form
                    name="basic"
                    labelCol={{
                        span: 8,
                    }}
                    wrapperCol={{
                        span: 16,
                    }}
                    initialValues={{
                        remember: true,
                    }}
                    onFinish={handleOk}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                    form={addForm}
                >
                    <Form.Item hidden name="id"
                    >
                        <Input placeholder='请输入' />
                    </Form.Item>
                    <Form.Item hidden name="key"
                    >
                        <Input placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        label="品牌名称"
                        name="name"
                        placeholder='请输入'
                        rules={[
                            {
                                required: true,
                                message: '请输入正确的品牌名称',
                            },
                        ]}
                    >
                        <Input placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        label="备注"
                        name="res"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your res!',
                            },
                        ]}
                    >
                        <Input placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        label="排序"
                        name="sort"
                        rules={[
                            {
                                required: true,
                                message: '11',
                            },
                        ]}
                    >
                        <Input placeholder='请输入' />
                    </Form.Item>

                    <Form.Item
                        label="创建时间"
                        name="date1"
                        initialValue={getTimes}
                    >
                        <Input placeholder='请输入' disabled />
                    </Form.Item>
                    <Form.Item >
                        <div style={{ width: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                            <Button type="primary" htmlType="submit" style={{ marginRight: '20px' }}>
                                确认
                            </Button>
                            <Button type="primary" onClick={onCannel}>
                                取消
                            </Button>
                        </div>
                    </Form.Item>

                </Form>
            </Modal>
            {/*  编辑*/}
            <Modal
                title={"编辑"}
                open={open2}
                closable={false}
                footer={null}
            >
                <Form
                    name="basic"
                    labelCol={{
                        span: 8,
                    }}
                    wrapperCol={{
                        span: 16,
                    }}
                    initialValues={{
                        remember: true,
                    }}
                    onFinish={handleOk2}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                    form={editForm}
                >
                    <Form.Item hidden name="id">
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="品牌名称"
                        name="name"
                        placeholder='请输入'
                        rules={[
                            {
                                required: true,
                                message: '请输入正确的品牌名称',
                            },
                        ]}
                    >
                        <Input placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        label="排序"
                        name="sort"
                        rules={[
                            {
                                required: true,
                                message: '11',
                            },
                        ]}
                    >
                        <Input placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        label="创建时间"
                        // style={{ display: 'none' }}
                        name="date1"
                    >
                        <Input placeholder='请输入' disabled />
                    </Form.Item>
                    <Form.Item >
                        <div style={{ width: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                            <Button type="primary" htmlType="submit" style={{ marginRight: '20px' }}>
                                确认
                            </Button>
                            <Button type="primary" onClick={onCannel2}>
                                取消
                            </Button>
                        </div>
                    </Form.Item>

                </Form>
            </Modal>

        </>
    )
}
export default connect(mapStateToProps, mapDispatchToProps)(BrandManagement);

